package com.sslpay.merchant.controller;

import com.sslpay.common.domain.BusinessException;
import com.sslpay.common.domain.RestResponse;
import com.sslpay.common.domain.UploadFileException;
import com.sslpay.common.util.PhoneUtil;
import com.sslpay.merchant.api.MerchantService;
import com.sslpay.merchant.api.dto.MerchantDTO;
import com.sslpay.merchant.common.domain.MerchantApplicationErrorCode;
import com.sslpay.merchant.common.domain.MerchantApplicationException;
import com.sslpay.merchant.common.util.SecurityUtil;
import com.sslpay.merchant.convert.MerchantDetailConvert;
import com.sslpay.merchant.convert.MerchantRegisterConvert;
import com.sslpay.merchant.service.FileService;
import com.sslpay.merchant.service.SmsService;
import com.sslpay.merchant.vo.MerchantDetailVO;
import com.sslpay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 描述：
 *
 * @author ssl
 * @create 2020/04/16 17:17
 */
@RestController
@RequestMapping("merchants")
@Api(value = "商户平台应用接口", tags = "商户平台应用接口", description = "商户平台应用接口")
public class MerchantController {
    @Reference
    private MerchantService merchantService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private FileService fileService;

    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询商户信息")
    public RestResponse getMerchantById(@PathVariable("id") Long id) throws MerchantApplicationException {
        if (null == id) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200102);
        }
        try {
            return RestResponse.success(merchantService.getMerchantById(id));
        } catch (BusinessException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200101, e);
        }
    }

    @ApiOperation("获取手机验证码")
    @ApiImplicitParam(value = "手机号", name = "phone", required = true, dataType = "string", paramType = "query")
    @GetMapping("/sms")
    public RestResponse getSMSCode(@RequestParam("phone") String phone) throws MerchantApplicationException {
        if (StringUtils.isBlank(phone)) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200104);
        }
        if (!PhoneUtil.isMatches(phone).booleanValue()) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200105);
        }
        try {
            return RestResponse.success(smsService.sendMsg(phone));
        } catch (BusinessException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200103, e);
        }
    }

    @PostMapping("/merchants/register")
    public RestResponse registerMerchant(@RequestBody MerchantRegisterVO merchantRegister) throws
            MerchantApplicationException {
        if (null == merchantRegister) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200107);
        }
        if (StringUtils.isBlank(merchantRegister.getMobile())) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200104);
        }
        if (!PhoneUtil.isMatches(merchantRegister.getMobile()).booleanValue()) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200105);
        }
        // 校验验证码
        try {
            smsService.checkVerifiyCode(merchantRegister.getVerifiykey(), merchantRegister.getVerifiyCode());
        } catch (BusinessException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200106, e);
        }
        // 注册商户
        try {
            merchantService.createMerchant(MerchantRegisterConvert.INSTANCE.voToDto(merchantRegister));
        } catch (BusinessException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200108, e);
        }
        return RestResponse.success(merchantRegister);
    }

    @ApiOperation("证件上传")
    @PostMapping("upload")
    public RestResponse upload(@ApiParam(value = "待上传文件", required = true)
                               @RequestParam("file") MultipartFile file) throws MerchantApplicationException {
        String originalFilename = file.getOriginalFilename();
        //扩展名

        String suffix = ".".concat(FilenameUtils.getExtension(originalFilename));
        //文件名称
        String filename = UUID.randomUUID() + suffix;
        byte[] fileByte;
        try {
            fileByte = file.getBytes();
        } catch (IOException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200109, e);
        }
        try {
            return RestResponse.success(fileService.upload(fileByte, filename));
        } catch (UploadFileException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200110, e);
        }
    }

    @ApiOperation("商户资质申请")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "merchantDetailVO", value = "商户认证资料", required = true, dataType =
                    "MerchantDetailVO", paramType = "body")}
    )
    @PostMapping("/my/merchant/save")
    public RestResponse saveMerchant(@RequestBody MerchantDetailVO merchantDetailVO) throws MerchantApplicationException {
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.voToDto(merchantDetailVO);
        try {
            merchantService.applyMerchant(merchantId, merchantDTO);
        } catch (BusinessException e) {
            throw new MerchantApplicationException(MerchantApplicationErrorCode.M_E_200111, e);
        }
        return RestResponse.success("资料提交成功");
    }
}
